package com.example.iotmanagerment26.controller;

import com.example.iotmanagerment26.OkHttpExample1;
import com.example.iotmanagerment26.domain.ActObj;
import com.example.iotmanagerment26.domain.Data;
import com.example.iotmanagerment26.domain.JsonData;
import com.example.iotmanagerment26.domain.Oprecord;
import com.example.iotmanagerment26.service.OprecordService;
import com.google.gson.Gson;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 作者：太难猫
 * 创建时间： 2025/6/4 17:58
 */
@RestController
@CrossOrigin
@RequestMapping(value="/businessCenter/v1/action")
@Tag(name="设备控制",description = "设备控制的接口")
public class BusinessController {
    @Autowired
    OkHttpExample1 okHttpExample1;
    @Autowired
    OprecordService oprecordService;
    @Autowired
    Gson gson;




    @PostMapping("/actjson")
    @Operation(summary = "发送json请求给设备进行相应操作")
    public Object sendjson(@RequestBody ActObj a1) {
        System.out.println(a1);
        String s1=gson.toJson(a1);
        System.out.println(s1);
        JsonData s=okHttpExample1
                .sendPOSTSync("http://129.204.4.65:30005/send_actobj_json",s1);
        System.out.println(s.toString());
        if(s.getCode()==1){
            //操作记录写入数据库
            a1.setSendtime(new Date());
            int result=oprecordService.insert(a1);
            if(result>=1){
                return new JsonData(1,result,"OK");
            }else{
                return new JsonData(0,result,"fail");
            }
        }
        else{
            return s;
        }

    }


    @GetMapping("/getData")
    @Operation(summary = "通过设备名字获取设备相关数据（一条）！")
    public JsonData getData(String device) {
        Data data=oprecordService.getData(device);
        if(data!=null){
            return new JsonData(1,data,"OK");
        }else{
            return new JsonData(0,data,"fail");
        }
    }

    @GetMapping("/getDataList")
    @Operation(summary = "通过设备名字获取设备相关数据(最近100条)！")
    public JsonData getDataList(String device) {
        List<Data> datas=oprecordService.getDataList(device);
        if(datas!=null && datas.size()!=0){
            return new JsonData(1,datas,"OK");
        }else{
            return new JsonData(0,datas,"fail");
        }
    }

    @GetMapping("/getOprecord")
    @Operation(summary = "通过设备名字获取设备操作记录（最近20条）！")
    public JsonData getOprecord(String device) {
        List<Oprecord> oprecords=oprecordService.getOprecord(device);
        if(oprecords!=null){
            return new JsonData(1,oprecords,"OK");
        }else{
            return new JsonData(0,oprecords,"fail");
        }
    }
}


